package com.community.common.config.shiro;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.PrintWriter;

/**
 * @author Administrator
 */
@Slf4j
public class ShiroPermissionsFilter extends FormAuthenticationFilter {

    /**
     * 重写验证失效后
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        if (isLoginRequest(request, response)) {
            if (isLoginSubmission(request, response)) {
                return executeLogin(request, response);
            } else {
                return true;
            }
        } else {
            String requestURI = getPathWithinApplication(request);
            HttpServletRequest httpServletRequest = (HttpServletRequest) request;
            if (isAjax(request)) {
                PrintWriter out = response.getWriter();
                out.print("8888");
            } else {
                response.setContentType("text/Html;charset=gb2312");
                PrintWriter out = response.getWriter();
                out.println("<script language='javascript' type='text/javascript'>");
                out.println("top.location.href='" + httpServletRequest.getContextPath() + "/page/login'");
                out.println("</script>");
            }
            return false;
        }
    }

    private static boolean isAjax(ServletRequest request) {
        String header = ((HttpServletRequest) request).getHeader("X-Requested-With");
        if ("XMLHttpRequest".equalsIgnoreCase(header)) {
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }
}
